import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'

// 创建一个axios的实例
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // request timeout
})

// 请求拦截器
request.interceptors.request.use(function(config) {
  const token = store.getters.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, function(error) {
  return Promise.reject(error)
})

// 响应拦截器
request.interceptors.response.use(function(response
) {
  const res = response.data
  const { message, success } = res
  if (!success) {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
  return res
}, function(error) {
  console.dir(error)
  if (error.response.status === 401 && error.response.data.code === 10002) {
    Message.error('登录会话已过期，请重新登录🙃')
    store.dispatch('user/logOut')
    router.push('/login')
  } else {
    Message.error(error.message)
  }
  return Promise.reject(error)
})
export default request // 导出axios实例
